import time

from selenium.webdriver.common.by import By

from util.logger import AutomationLogger

timeout = 30
poll = 2


class MobileTasks:
    def __init__(self, driver):
        self.driver = driver
        self.log_client = AutomationLogger()
        self.log_client.setUp()
        self.logger = self.log_client.logger

    def is_record_event_btn_exist(self):
        elem = self._find_elem_by_xpath('//android.widget.Button[contains(@resource-id,"id/trackEventButton")]')
        return elem is not None

    def click_next_btn(self):
        elems = self._find_elem_by_xpath('//XCUIElementTypeStaticText[@name="Next"]')
        self.logger.info('单击Next按钮')
        elems[0].click()

    def is_ctn_btn_exist(self):
        self.logger.info('查找Continue按钮...')
        elems = self._find_elem_by_xpath('//XCUIElementTypeStaticText[@name="Continue"]')
        return True if elems is not None and len(elems) > 0 else False

    def _find_elem_by_xpath(self, elem_xpath, time_out=timeout, raise_exception=True):
        start = time.time()
        elem = None
        while time.time() - start < time_out and elem is None:
            time.sleep(poll)
            try:
                elem = self.driver.find_elements(By.XPATH, elem_xpath)
            except Exception:
                self.logger.debug('Element not found, waiting...')

        if elem is None and raise_exception:
            raise LookupError(f'The element which xpath is {elem_xpath} could not be found')

        return elem
